package com.apartment.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.apartment.entity.User;
import com.apartment.service.house.HouseService;
import com.apartment.service.user.UserserviceImpl;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 2 * @Author: xy
 * 3 * @Date: 2021/09/11 下午 1:01:26
 */
@Controller
public class LoginController {


    @Autowired
    private HouseService houseService;
    @Autowired
    private UserserviceImpl userservice;

    @SneakyThrows
    @RequestMapping("/getCode")
    public void getCode(HttpServletRequest req, HttpServletResponse resp) {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(400, 200, 4, 4);
//      获取到验证码中的内容 ，保存在session中
        String code = captcha.getCode();
//      将图片传递给前端页面
        HttpSession session = req.getSession();
        session.setAttribute("code", code);
        captcha.write(resp.getOutputStream());
    }

    @RequestMapping("/login")
    public ModelAndView loginModel(String username, String pwd, String code) {
        ModelAndView mv = new ModelAndView();
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String requestCode = (String) request.getSession().getAttribute("code");

        if (!Objects.equals(code, requestCode)) {
            mv.addObject("msg", "验证码错误");
            mv.setViewName("login");
        } else {
            User user = userservice.login(username, pwd);
            if (user != null && user.getU_name() != null) {
                request.getSession().setAttribute("username", username);
                mv.addObject("user", username);
                mv.setViewName("admin");
            } else {
                mv.addObject("msg", "登陆失败");
                mv.setViewName("login");
            }
        }
        return mv;
    }


}
